<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="mini-vue3"><meta name="keywords" content="vue3 源码"><meta name="author" content="晟松"><meta name="copyright" content="晟松"><title>mini-vue3 | 晟松</title><link rel="shortcut icon" href="/logo.png"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?c34d81d53341febe06a155941e2df16d";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '5.4.0'
} </script><meta name="generator" content="Hexo 5.4.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#mini-vue3"><span class="toc-number">1.</span> <span class="toc-text">mini-vue3</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9E%E4%BE%8B%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-number">1.1.</span> <span class="toc-text">实例初始化</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%90%86%E4%B8%80%E4%B8%8B%E5%88%9D%E5%A7%8B%E5%8C%96%E6%97%B6%E5%80%99%E7%9A%84%E6%B5%81%E7%A8%8B"><span class="toc-number">1.1.1.</span> <span class="toc-text">理一下初始化时候的流程</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#createApp"><span class="toc-number">1.1.1.1.</span> <span class="toc-text">createApp</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#createVNode"><span class="toc-number">1.1.1.2.</span> <span class="toc-text">createVNode</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#render"><span class="toc-number">1.1.1.3.</span> <span class="toc-text">render</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#patch"><span class="toc-number">1.1.1.4.</span> <span class="toc-text">patch</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#mountComponent"><span class="toc-number">1.1.1.4.1.</span> <span class="toc-text">mountComponent</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#setupComponent"><span class="toc-number">1.1.1.5.</span> <span class="toc-text">setupComponent</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#setupRenderEffect"><span class="toc-number">1.1.1.6.</span> <span class="toc-text">setupRenderEffect</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#ReactiveEffect"><span class="toc-number">1.1.1.6.1.</span> <span class="toc-text">ReactiveEffect</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#h%E5%87%BD%E6%95%B0"><span class="toc-number">1.1.1.6.2.</span> <span class="toc-text">h函数</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%8F%92%E4%B8%80%E4%B8%AA-provide-inject"><span class="toc-number">1.1.1.7.</span> <span class="toc-text">插一个 provide&#x2F;inject</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E6%9B%B4%E6%96%B0%E6%B8%B2%E6%9F%93"><span class="toc-number">1.2.</span> <span class="toc-text">数据更新渲染</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%93%8D%E5%BA%94%E5%BC%8F%E9%80%BB%E8%BE%91"><span class="toc-number">1.2.1.</span> <span class="toc-text">响应式逻辑</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#reactive"><span class="toc-number">1.2.1.1.</span> <span class="toc-text">reactive</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#get"><span class="toc-number">1.2.1.1.1.</span> <span class="toc-text">get</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E4%BE%9D%E8%B5%96%E6%94%B6%E9%9B%86track"><span class="toc-number">1.2.1.1.2.</span> <span class="toc-text">依赖收集track</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#set"><span class="toc-number">1.2.1.1.3.</span> <span class="toc-text">set</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#computed"><span class="toc-number">1.2.1.2.</span> <span class="toc-text">computed</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#ref"><span class="toc-number">1.2.1.3.</span> <span class="toc-text">ref</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#%E4%BE%9D%E8%B5%96%E6%94%B6%E9%9B%86trackRefValue"><span class="toc-number">1.2.1.3.1.</span> <span class="toc-text">依赖收集trackRefValue</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E4%BE%9D%E8%B5%96%E8%A7%A6%E5%8F%91triggerRefValue"><span class="toc-number">1.2.1.3.2.</span> <span class="toc-text">依赖触发triggerRefValue</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#patch%E6%96%B0%E6%97%A7%E8%8A%82%E7%82%B9%E5%AF%B9%E6%AF%94"><span class="toc-number">1.2.1.4.</span> <span class="toc-text">patch新旧节点对比</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#element%E7%B1%BB%E5%9E%8B"><span class="toc-number">1.2.1.4.1.</span> <span class="toc-text">element类型</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#component%E7%B1%BB%E5%9E%8B%E5%AF%B9%E6%AF%94"><span class="toc-number">1.2.1.4.2.</span> <span class="toc-text">component类型对比</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#patch%E9%87%8D%E5%A4%B4%E6%88%8F"><span class="toc-number">1.2.1.5.</span> <span class="toc-text">patch重头戏</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#%E5%A5%BD%EF%BC%8C%E7%BB%A7%E7%BB%AD%E4%B8%8B%E4%B8%80%E4%B8%AA%E5%BE%AA%E7%8E%AF"><span class="toc-number">1.2.1.5.1.</span> <span class="toc-text">好，继续下一个循环</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E6%9C%80%E5%90%8E%E7%9A%84%E5%A4%84%E7%90%86"><span class="toc-number">1.2.1.5.2.</span> <span class="toc-text">最后的处理</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="/img/avatar.png"></div><div class="author-info__name text-center">晟松</div><div class="author-info__description text-center">晟松的博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://gitee.com/cheng_song">Gitee</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">52</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">45</span></a></div></div></div><div id="content-outer"><div id="top-container" style="background-image: url(/img/blog-bg.jpg)"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">晟松</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">Home</a><a class="site-page" href="/archives">Archives</a><a class="site-page" href="/tags">Tags</a><a class="site-page" href="/categories">Categories</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">mini-vue3</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2021-11-19</time><div class="post-meta-wordcount"><span>字数总计: </span><span class="word-count">7.9k</span><span class="post-meta__separator">|</span><span>阅读时长: 36 分钟</span></div></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><h2 id="mini-vue3"><a href="#mini-vue3" class="headerlink" title="mini-vue3"></a>mini-vue3</h2><p>这主要是对mini-vue这个项目的源码学习。这个项目就是去除vue3源码中的边界条件的判断，只看最主要的流程和代码。</p>
<p>本文就记录一下里面的一些让我觉得比较重要的代码进行记录</p>
<p><a target="_blank" rel="noopener" href="https://github.com/cuixiaorui/mini-vue#reactivity">mini-vue</a></p>
<h3 id="实例初始化"><a href="#实例初始化" class="headerlink" title="实例初始化"></a>实例初始化</h3><p><img src="https://user-images.githubusercontent.com/12064746/138114565-3e0eecbb-7fd0-4203-bf36-5e5fd8003ce0.png" alt="初始化流程"></p>
<p>patch这一段是不断地递归的渲染h函数创建出来的vnode，主要是里面的children属性</p>
<h4 id="理一下初始化时候的流程"><a href="#理一下初始化时候的流程" class="headerlink" title="理一下初始化时候的流程"></a>理一下初始化时候的流程</h4><p>这个是 <strong>example/helloWord</strong>里的例子，引入的是mini-vue.esm.js</p>
<p>首先是根据组件创建一个vue实例并挂载到根节点上</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// app.js</span></span><br><span class="line"><span class="keyword">import</span> &#123; h, ref &#125; <span class="keyword">from</span> <span class="string">&quot;../../lib/mini-vue.esm.js&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> count = ref(<span class="number">11</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> HelloWorld = &#123;</span><br><span class="line">  <span class="attr">name</span>: <span class="string">&quot;HelloWorld&quot;</span>,</span><br><span class="line">  <span class="function"><span class="title">setup</span>(<span class="params"></span>)</span> &#123;&#125;,</span><br><span class="line">  <span class="function"><span class="title">render</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> h(</span><br><span class="line">      <span class="string">&quot;div&quot;</span>,</span><br><span class="line">      &#123; <span class="attr">tId</span>: <span class="string">&quot;helloWorld&quot;</span> &#125;,</span><br><span class="line">      <span class="string">`hello world: count: <span class="subst">$&#123;count.value&#125;</span>`</span></span><br><span class="line">    );</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="attr">name</span>: <span class="string">&quot;App&quot;</span>,</span><br><span class="line">  <span class="function"><span class="title">setup</span>(<span class="params"></span>)</span> &#123;&#125;,</span><br><span class="line">  <span class="function"><span class="title">render</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> h(<span class="string">&quot;div&quot;</span>, &#123; <span class="attr">tId</span>: <span class="number">1</span> &#125;, [h(<span class="string">&quot;p&quot;</span>, &#123;&#125;, <span class="string">&quot;主页&quot;</span>), h(HelloWorld)]);</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// main.js</span></span><br><span class="line"><span class="keyword">import</span> &#123; createApp &#125; <span class="keyword">from</span> <span class="string">&quot;../../lib/mini-vue.esm.js&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> App <span class="keyword">from</span> <span class="string">&quot;./App.js&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> rootContainer = <span class="built_in">document</span>.querySelector(<span class="string">&quot;#root&quot;</span>);</span><br><span class="line">createApp(App).mount(rootContainer);</span><br></pre></td></tr></table></figure>

<p>然后就是内部的实现了</p>
<h5 id="createApp"><a href="#createApp" class="headerlink" title="createApp"></a>createApp</h5><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> createApp = <span class="function">(<span class="params">rootComponent</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> app = &#123;</span><br><span class="line">        <span class="attr">_component</span>: rootComponent,</span><br><span class="line">        <span class="function"><span class="title">mount</span>(<span class="params">rootContainer</span>)</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;基于根组件创建 vnode&quot;</span>);</span><br><span class="line">            <span class="keyword">const</span> vnode = createVNode(rootComponent);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;调用 render，基于 vnode 进行开箱&quot;</span>);</span><br><span class="line">            render(vnode, rootContainer);</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">return</span> app;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>createApp就是使用根据传来的App组件创建vnode，并render到rootContainer上</p>
<h5 id="createVNode"><a href="#createVNode" class="headerlink" title="createVNode"></a>createVNode</h5><p>首先看下shapeFlag各代表的类型</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">ShapeFlags[ShapeFlags[<span class="string">&quot;ELEMENT&quot;</span>] = <span class="number">1</span>] = <span class="string">&quot;ELEMENT&quot;</span>;</span><br><span class="line">ShapeFlags[ShapeFlags[<span class="string">&quot;STATEFUL_COMPONENT&quot;</span>] = <span class="number">4</span>] = <span class="string">&quot;STATEFUL_COMPONENT&quot;</span>;</span><br><span class="line">ShapeFlags[ShapeFlags[<span class="string">&quot;TEXT_CHILDREN&quot;</span>] = <span class="number">8</span>] = <span class="string">&quot;TEXT_CHILDREN&quot;</span>;</span><br><span class="line">ShapeFlags[ShapeFlags[<span class="string">&quot;ARRAY_CHILDREN&quot;</span>] = <span class="number">16</span>] = <span class="string">&quot;ARRAY_CHILDREN&quot;</span>;</span><br><span class="line">ShapeFlags[ShapeFlags[<span class="string">&quot;SLOTS_CHILDREN&quot;</span>] = <span class="number">32</span>] = <span class="string">&quot;SLOTS_CHILDREN&quot;</span>;</span><br></pre></td></tr></table></figure>



<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> createVNode = <span class="function"><span class="keyword">function</span> (<span class="params">type, props, children</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> vnode = &#123;</span><br><span class="line">        <span class="attr">el</span>: <span class="literal">null</span>,</span><br><span class="line">        <span class="attr">component</span>: <span class="literal">null</span>,</span><br><span class="line">        <span class="attr">key</span>: props === <span class="literal">null</span> || props === <span class="keyword">void</span> <span class="number">0</span> ? <span class="keyword">void</span> <span class="number">0</span> : props.key,</span><br><span class="line">        type,</span><br><span class="line">        <span class="attr">props</span>: props || &#123;&#125;,</span><br><span class="line">        children,</span><br><span class="line">        <span class="attr">shapeFlag</span>: getShapeFlag(type),</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(children)) &#123;</span><br><span class="line">        vnode.shapeFlag |= <span class="number">16</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> children === <span class="string">&quot;string&quot;</span>) &#123;</span><br><span class="line">        vnode.shapeFlag |= <span class="number">8</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    normalizeChildren(vnode, children);</span><br><span class="line">    <span class="keyword">return</span> vnode;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getShapeFlag</span>(<span class="params">type</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">typeof</span> type === <span class="string">&quot;string&quot;</span></span><br><span class="line">        ? <span class="number">1</span></span><br><span class="line">        : <span class="number">4</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">normalizeChildren</span>(<span class="params">vnode, children</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> children === <span class="string">&quot;object&quot;</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (vnode.shapeFlag &amp; <span class="number">1</span>) ;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            vnode.shapeFlag |= <span class="number">32</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意第一次进来的时候，只有type这个参数，shapeFlag为4，代表根组件？</p>
<h5 id="render"><a href="#render" class="headerlink" title="render"></a>render</h5><p>然后就是将vnode挂载到rootContainer上面，这一步调用了patch，并将第一个参数设置为null，因为初始化的时候，没有旧的需要比对的节点</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> Text = <span class="built_in">Symbol</span>(<span class="string">&quot;Text&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> render = <span class="function">(<span class="params">vnode, container</span>) =&gt;</span> &#123;</span><br><span class="line">    debug.mainPath(<span class="string">&quot;调用 patch&quot;</span>)();</span><br><span class="line">    patch(<span class="literal">null</span>, vnode, container);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h5 id="patch"><a href="#patch" class="headerlink" title="patch"></a>patch</h5><p>似乎这个patch里面并没有对两个节点的type不同的时候进行操作，默认是相同的</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">patch</span>(<span class="params">n1, n2, container = <span class="literal">null</span>, parentComponent = <span class="literal">null</span></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; type, shapeFlag &#125; = n2;</span><br><span class="line">    <span class="keyword">switch</span> (type) &#123;</span><br><span class="line">        <span class="keyword">case</span> Text:</span><br><span class="line">            processText(n1, n2, container);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">if</span> (shapeFlag &amp; <span class="number">1</span>) &#123;</span><br><span class="line">                <span class="built_in">console</span>.log(<span class="string">&quot;处理 element&quot;</span>);</span><br><span class="line">                processElement(n1, n2, container);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (shapeFlag &amp; <span class="number">4</span>) &#123;</span><br><span class="line">                <span class="built_in">console</span>.log(<span class="string">&quot;处理 component&quot;</span>);</span><br><span class="line">                processComponent(n1, n2, container, parentComponent);</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后因为shapeFlag最开始是4，所以就去处理 component</p>
<p>这里就判断是挂载还是更新</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">processComponent</span>(<span class="params">n1, n2, container, parentComponent</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!n1) &#123;</span><br><span class="line">        mountComponent(n2, container, parentComponent);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        updateComponent(n1, n2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后就去mount</p>
<h6 id="mountComponent"><a href="#mountComponent" class="headerlink" title="mountComponent"></a>mountComponent</h6><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">mountComponent</span>(<span class="params">initialVNode, container, parentComponent</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent));</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`创建组件实例:<span class="subst">$&#123;instance.type.name&#125;</span>`</span>);</span><br><span class="line">    setupComponent(instance);</span><br><span class="line">    setupRenderEffect(instance, initialVNode, container);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>先根据vnode创建组件实例</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">emit</span>(<span class="params">instance, event, ...rawArgs</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// event表示事件名</span></span><br><span class="line">    <span class="keyword">const</span> props = instance.props;</span><br><span class="line">    <span class="comment">// 下面这一行就是对事件名进行一个标准化的处理。如event=&#x27;mine-word&#x27;，处理的结果就是onMineWord</span></span><br><span class="line">    <span class="keyword">const</span> handlerName = toHandlerKey(camelize(event));</span><br><span class="line">    <span class="keyword">const</span> handler = props[handlerName];</span><br><span class="line">    <span class="keyword">if</span> (handler) &#123;</span><br><span class="line">        handler(...rawArgs);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createComponentInstance</span>(<span class="params">vnode, parent</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> instance = &#123;</span><br><span class="line">        <span class="attr">type</span>: vnode.type,</span><br><span class="line">        vnode,</span><br><span class="line">        <span class="attr">next</span>: <span class="literal">null</span>,</span><br><span class="line">        <span class="attr">props</span>: &#123;&#125;,</span><br><span class="line">        parent,</span><br><span class="line">        <span class="attr">provides</span>: parent ? parent.provides : &#123;&#125;,</span><br><span class="line">        <span class="attr">proxy</span>: <span class="literal">null</span>,</span><br><span class="line">        <span class="attr">isMounted</span>: <span class="literal">false</span>,</span><br><span class="line">        <span class="attr">attrs</span>: &#123;&#125;,</span><br><span class="line">        <span class="attr">slots</span>: &#123;&#125;,</span><br><span class="line">        <span class="attr">ctx</span>: &#123;&#125;,</span><br><span class="line">        <span class="attr">setupState</span>: &#123;&#125;,</span><br><span class="line">        <span class="attr">emit</span>: <span class="function">() =&gt;</span> &#123; &#125;,</span><br><span class="line">    &#125;;</span><br><span class="line">    instance.ctx = &#123;</span><br><span class="line">        <span class="attr">_</span>: instance,</span><br><span class="line">    &#125;;</span><br><span class="line">    instance.emit = emit.bind(<span class="literal">null</span>, instance);</span><br><span class="line">    <span class="keyword">return</span> instance;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>里面的emit就是触发父组件通过props传来的事件函数</p>
<h5 id="setupComponent"><a href="#setupComponent" class="headerlink" title="setupComponent"></a>setupComponent</h5><p>然后初始化组件的setup，包括props，slots</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">setupComponent</span>(<span class="params">instance</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; props, children &#125; = instance.vnode;</span><br><span class="line">    initProps(instance, props);</span><br><span class="line">    initSlots(instance, children);</span><br><span class="line">    setupStatefulComponent(instance);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initProps</span>(<span class="params">instance, rawProps</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;initProps&quot;</span>);</span><br><span class="line">    instance.props = rawProps;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initSlots</span>(<span class="params">instance, children</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; vnode &#125; = instance;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;初始化 slots&quot;</span>);</span><br><span class="line">    <span class="comment">// 32表示 slot chilidren</span></span><br><span class="line">    <span class="keyword">if</span> (vnode.shapeFlag &amp; <span class="number">32</span>) &#123;</span><br><span class="line">        <span class="comment">// (instance.slots = &#123;&#125;) 相当于先赋值&#123;&#125;，然后将instance.slots当参数进行传递</span></span><br><span class="line">        normalizeObjectSlots(children, (instance.slots = &#123;&#125;));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> normalizeObjectSlots = <span class="function">(<span class="params">rawSlots, slots</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">in</span> rawSlots) &#123;</span><br><span class="line">        <span class="keyword">const</span> value = rawSlots[key];</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">typeof</span> value === <span class="string">&quot;function&quot;</span>) &#123;</span><br><span class="line">            slots[key] = value;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>然后就是将实例proxy且挂到自己的实例上，并将props和context当做参数传递给组件的setup中进行执行</p>
<p>TODO：里面的setCurrentInstance还不知道用处是干什么？— 是为了实现provide/inject而设置的</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">setupStatefulComponent</span>(<span class="params">instance</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;创建 proxy&quot;</span>);</span><br><span class="line">    <span class="comment">// instance.ctx在创建时就是instance自己</span></span><br><span class="line">    instance.proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(instance.ctx, PublicInstanceProxyHandlers);</span><br><span class="line">    <span class="keyword">const</span> Component = instance.type;</span><br><span class="line">    <span class="keyword">const</span> &#123; setup &#125; = Component;</span><br><span class="line">    <span class="keyword">if</span> (setup) &#123;</span><br><span class="line">        setCurrentInstance(instance);</span><br><span class="line">        <span class="keyword">const</span> setupContext = createSetupContext(instance);</span><br><span class="line">        <span class="comment">// 这里就是setup的两个参数了，第一个是props，第二个是ctx</span></span><br><span class="line">        <span class="comment">// shallowReadonly是将props proxy一下，让其变为只读，而不能修改，应该是防止子组件修改父组件传来的值造成影响</span></span><br><span class="line">        <span class="comment">// setupResult就是setup return的那一个对象</span></span><br><span class="line">        <span class="keyword">const</span> setupResult = setup &amp;&amp; setup(shallowReadonly(instance.props), setupContext);</span><br><span class="line">        <span class="comment">// console.log(&#x27;setupResult: &#x27;, setupResult);</span></span><br><span class="line">        setCurrentInstance(<span class="literal">null</span>);</span><br><span class="line">        handleSetupResult(instance, setupResult);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        finishComponentSetup(instance);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>PublicInstanceProxyHandlers主要是对几个$开头的属性进行返回</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> publicPropertiesMap = &#123;</span><br><span class="line">    <span class="attr">$el</span>: <span class="function">(<span class="params">i</span>) =&gt;</span> i.vnode.el,</span><br><span class="line">    <span class="attr">$emit</span>: <span class="function">(<span class="params">i</span>) =&gt;</span> i.emit,</span><br><span class="line">    <span class="attr">$slots</span>: <span class="function">(<span class="params">i</span>) =&gt;</span> i.slots,</span><br><span class="line">    <span class="attr">$props</span>: <span class="function">(<span class="params">i</span>) =&gt;</span> i.props,</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">const</span> PublicInstanceProxyHandlers = &#123;</span><br><span class="line">    <span class="function"><span class="title">get</span>(<span class="params">&#123; _: instance &#125;, key</span>)</span> &#123;</span><br><span class="line">        <span class="comment">// 注意这里将setup函数的返回值给解构出来了，让h函数可访问到</span></span><br><span class="line">        <span class="keyword">const</span> &#123; setupState &#125; = instance;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`触发 proxy hook , key -&gt; : <span class="subst">$&#123;key&#125;</span>`</span>);</span><br><span class="line">        <span class="keyword">if</span> (key !== <span class="string">&quot;$&quot;</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (key <span class="keyword">in</span> setupState) &#123;</span><br><span class="line">                <span class="keyword">return</span> setupState[key];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">const</span> publicGetter = publicPropertiesMap[key];</span><br><span class="line">        <span class="keyword">if</span> (publicGetter) &#123;</span><br><span class="line">            <span class="keyword">return</span> publicGetter(instance);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="function"><span class="title">set</span>(<span class="params">&#123; _: instance &#125;, key, value</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> &#123; setupState &#125; = instance;</span><br><span class="line">        <span class="keyword">if</span> (setupState !== &#123;&#125; &amp;&amp; hasOwn(setupState, key)) &#123;</span><br><span class="line">            setupState[key] = value;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>然后就是根据实例创建setup的第二个参数context</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createSetupContext</span>(<span class="params">instance</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;初始化 setup context&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        <span class="attr">attrs</span>: instance.attrs,</span><br><span class="line">        <span class="attr">slots</span>: instance.slots,</span><br><span class="line">        <span class="attr">emit</span>: instance.emit,</span><br><span class="line">        <span class="attr">expose</span>: <span class="function">() =&gt;</span> &#123; &#125;,</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>后面就是将props处理一下然后和context一起传入组件的setup函数执行，并返回结果</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> setupResult = setup &amp;&amp; setup(shallowReadonly(instance.props), setupContext);</span><br><span class="line"></span><br><span class="line">handleSetupResult(instance, setupResult);</span><br></pre></td></tr></table></figure>

<p>shallowReadonly是为了传来的props只读。防止子组件修改了父组件的值</p>
<p>然后就是对这个返回值处理一下ref创建的变量，让其可以在template里面不使用 .value的语法</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">handleSetupResult</span>(<span class="params">instance, setupResult</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> setupResult === <span class="string">&quot;function&quot;</span>) &#123;</span><br><span class="line">        instance.render = setupResult;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> setupResult === <span class="string">&quot;object&quot;</span>) &#123;</span><br><span class="line">        <span class="comment">// proxyRefs似乎是让ref创建出来的数据解构一下，让其不在template里面使用 .value 的语法</span></span><br><span class="line">        <span class="comment">// 注意这里将setupResult放在了instance里面</span></span><br><span class="line">        instance.setupState = proxyRefs(setupResult);</span><br><span class="line">    &#125;</span><br><span class="line">    finishComponentSetup(instance);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后将render挂在到实例上</p>
<p>TODO：这一步我还不知道啥意思。— 用于组件的渲染</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">finishComponentSetup</span>(<span class="params">instance</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> Component = instance.type;</span><br><span class="line">    <span class="keyword">if</span> (!instance.render) &#123;</span><br><span class="line">        instance.render = Component.render;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// App.js</span></span><br><span class="line"><span class="function"><span class="title">render</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> h(<span class="string">&quot;div&quot;</span>, &#123; <span class="attr">tId</span>: <span class="number">1</span> &#125;, [h(<span class="string">&quot;p&quot;</span>, &#123;&#125;, <span class="string">&quot;主页&quot;</span>), h(HelloWorld)])</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h5 id="setupRenderEffect"><a href="#setupRenderEffect" class="headerlink" title="setupRenderEffect"></a>setupRenderEffect</h5><p>这里就是通过instance.render获得其render函数所创建出来的vnode（子组件），并调用patch递归初始化子组件</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">setupRenderEffect(instance, initialVNode, container);</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">setupRenderEffect</span>(<span class="params">instance, initialVNode, container</span>) </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">componentUpdateFn</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!instance.isMounted) &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;调用 render,获取 subTree&quot;</span>);</span><br><span class="line">            <span class="keyword">const</span> proxyToUse = instance.proxy;</span><br><span class="line">            <span class="comment">// 初始化时 instance.render = Component.render;</span></span><br><span class="line">            <span class="comment">// render函数是使用h函数创建出vnode</span></span><br><span class="line">            <span class="comment">// 这里传入proxyToUse当做this是因为可能在h函数里面会访问到setup函数返回的数据</span></span><br><span class="line">            <span class="keyword">const</span> subTree = (instance.subTree = instance.render.call(proxyToUse, proxyToUse));</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;subTree&quot;</span>, subTree);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;instance.type.name&#125;</span>:触发 beforeMount hook`</span>);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;instance.type.name&#125;</span>:触发 onVnodeBeforeMount hook`</span>);</span><br><span class="line">            patch(<span class="literal">null</span>, subTree, container, instance);</span><br><span class="line">            initialVNode.el = subTree.el;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;instance.type.name&#125;</span>:触发 mounted hook`</span>);</span><br><span class="line">            instance.isMounted = <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;调用更新逻辑&quot;</span>);</span><br><span class="line">            <span class="keyword">const</span> &#123; next, vnode &#125; = instance;</span><br><span class="line">            <span class="keyword">if</span> (next) &#123;</span><br><span class="line">                next.el = vnode.el;</span><br><span class="line">                updateComponentPreRender(instance, next);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">const</span> proxyToUse = instance.proxy;</span><br><span class="line">            <span class="keyword">const</span> nextTree = instance.render.call(proxyToUse, proxyToUse);</span><br><span class="line">            <span class="keyword">const</span> prevTree = instance.subTree;</span><br><span class="line">            instance.subTree = nextTree;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;beforeUpdated hook&quot;</span>);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;onVnodeBeforeUpdate hook&quot;</span>);</span><br><span class="line">            patch(prevTree, nextTree, prevTree.el, instance);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;updated hook&quot;</span>);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;onVnodeUpdated hook&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    instance.update = effect(componentUpdateFn, &#123;</span><br><span class="line">        <span class="attr">scheduler</span>: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            queueJob(instance.update);</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>TODO：还不知道这个effect的作用。就是响应式的effct收集依赖，提供一个可以进行更新的入口</p>
<h6 id="ReactiveEffect"><a href="#ReactiveEffect" class="headerlink" title="ReactiveEffect"></a>ReactiveEffect</h6><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ReactiveEffect</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">fn, scheduler</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.fn = fn;</span><br><span class="line">        <span class="built_in">this</span>.scheduler = scheduler;</span><br><span class="line">        <span class="built_in">this</span>.active = <span class="literal">true</span>;</span><br><span class="line">        <span class="built_in">this</span>.deps = [];</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;创建 ReactiveEffect 对象&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="title">run</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;run&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span> (!<span class="built_in">this</span>.active) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">this</span>.fn();</span><br><span class="line">        &#125;</span><br><span class="line">        shouldTrack = <span class="literal">true</span>;</span><br><span class="line">        activeEffect = <span class="built_in">this</span>;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;执行用户传入的 fn&quot;</span>);</span><br><span class="line">        <span class="keyword">const</span> result = <span class="built_in">this</span>.fn();</span><br><span class="line">        shouldTrack = <span class="literal">false</span>;</span><br><span class="line">        activeEffect = <span class="literal">undefined</span>;</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="title">stop</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="built_in">this</span>.active) &#123;</span><br><span class="line">            cleanupEffect(<span class="built_in">this</span>);</span><br><span class="line">            <span class="keyword">if</span> (<span class="built_in">this</span>.onStop) &#123;</span><br><span class="line">                <span class="built_in">this</span>.onStop();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">this</span>.active = <span class="literal">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">effect</span>(<span class="params">fn, options = &#123;&#125;</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> _effect = <span class="keyword">new</span> ReactiveEffect(fn);</span><br><span class="line">    extend(_effect, options);</span><br><span class="line">    _effect.run();</span><br><span class="line">    <span class="keyword">const</span> runner = _effect.run.bind(_effect);</span><br><span class="line">    runner.effect = _effect;</span><br><span class="line">    <span class="keyword">return</span> runner;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面的run就是执行传来的fn，就是componentUpdateFn</p>
<p>最开始instance.isMounted为空，所以进行初始化</p>
<p>先使用instance的proxy当做执行环境给instance.render进行执行，也就是使用<strong>h函数</strong>创建vnode</p>
<h6 id="h函数"><a href="#h函数" class="headerlink" title="h函数"></a>h函数</h6><p>h函数就是调用createVNode生成vnode</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> h = <span class="function">(<span class="params">type, props, children</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> createVNode(type, props, children);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//App.js</span></span><br><span class="line">h(<span class="string">&quot;div&quot;</span>, &#123; <span class="attr">tId</span>: <span class="number">1</span> &#125;, [h(<span class="string">&quot;p&quot;</span>, &#123;&#125;, <span class="string">&quot;主页&quot;</span>), h(HelloWorld)]);</span><br></pre></td></tr></table></figure>

<p>因为type是一个string，且含有children，所以这个创建出来的vnode的shapeFlag为17。</p>
<p>然后获取到子组件的vnode后调用patch，因为<strong>shapeFlag为17</strong>，所以根据代码进行processElement</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">processElement</span>(<span class="params">n1, n2, container</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!n1) &#123;</span><br><span class="line">        mountElement(n2, container);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        updateElement(n1, n2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">mountElement</span>(<span class="params">vnode, container</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; shapeFlag, props &#125; = vnode;</span><br><span class="line">    <span class="keyword">const</span> el = (vnode.el = hostCreateElement(vnode.type));</span><br><span class="line">    <span class="keyword">if</span> (shapeFlag &amp; <span class="number">8</span>) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`处理文本:<span class="subst">$&#123;vnode.children&#125;</span>`</span>);</span><br><span class="line">        hostSetElementText(el, vnode.children);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (shapeFlag &amp; <span class="number">16</span>) &#123;</span><br><span class="line">        <span class="comment">// 注意这里的第二个参数是 el</span></span><br><span class="line">        mountChildren(vnode.children, el);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (props) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">in</span> props) &#123;</span><br><span class="line">            <span class="keyword">const</span> nextVal = props[key];</span><br><span class="line">            hostPatchProp(el, key, <span class="literal">null</span>, nextVal);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;vnodeHook  -&gt; onVnodeBeforeMount&quot;</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;DirectiveHook  -&gt; beforeMount&quot;</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;transition  -&gt; beforeEnter&quot;</span>);</span><br><span class="line">    hostInsert(el, container);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;vnodeHook  -&gt; onVnodeMounted&quot;</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;DirectiveHook  -&gt; mounted&quot;</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;transition  -&gt; enter&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>显示根据type创建实际的浏览器节点</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">hostCreateElement</span>(<span class="params">type</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;hostCreateElement&quot;</span>, type);</span><br><span class="line">    <span class="keyword">const</span> element = <span class="built_in">document</span>.createElement(type);</span><br><span class="line">    <span class="keyword">return</span> element;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后根据节点类型和是否有props进行处理</p>
<p>如果是文本节点就直接设置上去</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">hostSetElementText</span>(<span class="params">el, text</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;hostSetElementText&quot;</span>, el, text);</span><br><span class="line">    el.textContent = text;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果是子组件节点就递归的挂载上去</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">mountChildren</span>(<span class="params">children, container</span>) </span>&#123;</span><br><span class="line">    children.forEach(<span class="function">(<span class="params">VNodeChild</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;mountChildren:&quot;</span>, VNodeChild);</span><br><span class="line">        patch(<span class="literal">null</span>, VNodeChild, container);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果有props就设置到el上</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">hostPatchProp</span>(<span class="params">el, key, preValue, nextValue</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`hostPatchProp 设置属性:<span class="subst">$&#123;key&#125;</span> 值:<span class="subst">$&#123;nextValue&#125;</span>`</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`key: <span class="subst">$&#123;key&#125;</span> 之前的值是:<span class="subst">$&#123;preValue&#125;</span>`</span>);</span><br><span class="line">    <span class="comment">// isOn是判断是否以on开头，如onClick，进行事件处理</span></span><br><span class="line">    <span class="keyword">if</span> (isOn(key)) &#123;</span><br><span class="line">        <span class="keyword">const</span> invokers = el._vei || (el._vei = &#123;&#125;);</span><br><span class="line">        <span class="keyword">const</span> existingInvoker = invokers[key];</span><br><span class="line">        <span class="keyword">if</span> (nextValue &amp;&amp; existingInvoker) &#123;</span><br><span class="line">            existingInvoker.value = nextValue;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">const</span> eventName = key.slice(<span class="number">2</span>).toLowerCase();</span><br><span class="line">            <span class="keyword">if</span> (nextValue) &#123;</span><br><span class="line">                <span class="keyword">const</span> invoker = (invokers[key] = nextValue);</span><br><span class="line">                el.addEventListener(eventName, invoker);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                el.removeEventListener(eventName, existingInvoker);</span><br><span class="line">                invokers[key] = <span class="literal">undefined</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (nextValue === <span class="literal">null</span> || nextValue === <span class="string">&quot;&quot;</span>) &#123;</span><br><span class="line">            el.removeAttribute(key);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            el.setAttribute(key, nextValue);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>里面的existingInvoker应该是为了性能优化？</p>
<p>然后根据是否有nextValue即新的值，判断是新增事件监听还是移出</p>
<p>后面就是触发一系列的钩子，beforemount（vnodeHook、DirectiveHook、transition-beforeEnter）；mounted（vnodeHook、DirectiveHook、transition-enter）</p>
<p>然后就是将el<strong>实际</strong>的挂载到container上</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">hostInsert</span>(<span class="params">child, parent, anchor = <span class="literal">null</span></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;hostInsert&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span> (anchor) &#123;</span><br><span class="line">        parent.insertBefore(child, anchor);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        parent.appendChild(child);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>至此，初始化的流程基本结束了，下一步就是理解更新的逻辑了</p>
<h5 id="插一个-provide-inject"><a href="#插一个-provide-inject" class="headerlink" title="插一个 provide/inject"></a>插一个 provide/inject</h5><p>其执行是在setup函数里面的，所以可以通过上面的setupComponent的setupStatefulComponent获取到instance</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">provide</span>(<span class="params">key, value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> _a;</span><br><span class="line">    <span class="keyword">const</span> currentInstance = getCurrentInstance();</span><br><span class="line">    <span class="keyword">if</span> (currentInstance) &#123;</span><br><span class="line">        <span class="keyword">let</span> &#123; provides &#125; = currentInstance;</span><br><span class="line">        <span class="comment">// 下面这一句就是如果currentInstance.parent为null，则返回一个true，然后将provide的key和value设到自己的instance上；如果不是null，则将parent的provides给继承下来，然后再对自己的setup里面的provide的key和value进行设置</span></span><br><span class="line">        <span class="keyword">const</span> parentProvides = (_a = currentInstance.parent) === <span class="literal">null</span> || _a === <span class="keyword">void</span> <span class="number">0</span> ? <span class="keyword">void</span> <span class="number">0</span> : _a.provides;</span><br><span class="line">        <span class="keyword">if</span> (parentProvides === provides) &#123;</span><br><span class="line">            <span class="comment">// Object.create以其参数为原型，创建一个对象，使用了原型链</span></span><br><span class="line">            provides = currentInstance.provides = <span class="built_in">Object</span>.create(parentProvides);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 因为是解构出来的，所以最终还是变化在instance上</span></span><br><span class="line">        provides[key] = value;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">inject</span>(<span class="params">key, defaultValue</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> _a;</span><br><span class="line">    <span class="keyword">const</span> currentInstance = getCurrentInstance();</span><br><span class="line">    <span class="keyword">if</span> (currentInstance) &#123;</span><br><span class="line">        <span class="comment">// 这里的逻辑与上面差不多，就是判断是否有parent节点，如果没有的话，那么自己肯定不会有数据可以inject到</span></span><br><span class="line">        <span class="keyword">const</span> provides = (_a = currentInstance.parent) === <span class="literal">null</span> || _a === <span class="keyword">void</span> <span class="number">0</span> ? <span class="keyword">void</span> <span class="number">0</span> : _a.provides;</span><br><span class="line">        <span class="keyword">if</span> (key <span class="keyword">in</span> provides) &#123;</span><br><span class="line">            <span class="keyword">return</span> provides[key];</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (defaultValue) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">typeof</span> defaultValue === <span class="string">&quot;function&quot;</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> defaultValue();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> defaultValue;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 注意一下provides是怎么创建出来的</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createComponentInstance</span>(<span class="params">vnode, parent</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> instance = &#123;</span><br><span class="line">        <span class="attr">type</span>: vnode.type,</span><br><span class="line">        vnode,</span><br><span class="line">        <span class="attr">next</span>: <span class="literal">null</span>,</span><br><span class="line">        <span class="attr">props</span>: &#123;&#125;,</span><br><span class="line">        parent,</span><br><span class="line">        <span class="attr">provides</span>: parent ? parent.provides : &#123;&#125;,</span><br><span class="line">        <span class="attr">proxy</span>: <span class="literal">null</span>,</span><br><span class="line">        <span class="attr">isMounted</span>: <span class="literal">false</span>,</span><br><span class="line">        <span class="attr">attrs</span>: &#123;&#125;,</span><br><span class="line">        <span class="attr">slots</span>: &#123;&#125;,</span><br><span class="line">        <span class="attr">ctx</span>: &#123;&#125;,</span><br><span class="line">        <span class="attr">setupState</span>: &#123;&#125;,</span><br><span class="line">        <span class="attr">emit</span>: <span class="function">() =&gt;</span> &#123; &#125;,</span><br><span class="line">    &#125;;</span><br><span class="line">    instance.ctx = &#123;</span><br><span class="line">        <span class="attr">_</span>: instance,</span><br><span class="line">    &#125;;</span><br><span class="line">    instance.emit = emit.bind(<span class="literal">null</span>, instance);</span><br><span class="line">    <span class="keyword">return</span> instance;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意这个使用了原型链的特性，使得inject可以通过原型获取每一层provide的数据</p>
<h3 id="数据更新渲染"><a href="#数据更新渲染" class="headerlink" title="数据更新渲染"></a>数据更新渲染</h3><p>这个就是以 <strong>example/componentUpdate</strong> 文件作为示例</p>
<img src="C:\Users\shengsong.jiang\AppData\Roaming\Typora\typora-user-images\image-20211104155042428.png" alt="image-20211104155042428" style="zoom:80%;" />

<p>点击按钮后，修改ref的值，使得child123变为child456</p>
<p>本文件</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 在 render 中使用 proxy 调用 emit 函数</span></span><br><span class="line"><span class="comment">// 也可以直接使用 this</span></span><br><span class="line"><span class="comment">// 验证 proxy 的实现逻辑</span></span><br><span class="line"><span class="keyword">import</span> &#123; h, ref &#125; <span class="keyword">from</span> <span class="string">&quot;../../lib/mini-vue.esm.js&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> Child <span class="keyword">from</span> <span class="string">&quot;./Child.js&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="attr">name</span>: <span class="string">&quot;App&quot;</span>,</span><br><span class="line">  <span class="function"><span class="title">setup</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> msg = ref(<span class="string">&quot;123&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> changeChildProps = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      msg.value = <span class="string">&quot;456&quot;</span>;</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> &#123; msg, changeChildProps &#125;;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">render</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> h(<span class="string">&quot;div&quot;</span>, &#123;&#125;, [</span><br><span class="line">      h(<span class="string">&quot;div&quot;</span>, &#123;&#125;, <span class="string">&quot;你好&quot;</span>),</span><br><span class="line">      h(</span><br><span class="line">        <span class="string">&quot;button&quot;</span>,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">onClick</span>: <span class="built_in">this</span>.changeChildProps,</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="string">&quot;change child props&quot;</span></span><br><span class="line">      ),</span><br><span class="line">      h(Child, &#123;</span><br><span class="line">        <span class="attr">msg</span>: <span class="built_in">this</span>.msg,</span><br><span class="line">      &#125;),</span><br><span class="line">    ]);</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>使用ref创建了一个响应式变量msg，同时含有一个button和点击事件去修改这个msg的值，去触发vue的响应式变量的更新逻辑</p>
<h4 id="响应式逻辑"><a href="#响应式逻辑" class="headerlink" title="响应式逻辑"></a>响应式逻辑</h4><p>现在先理一下响应式这边的逻辑吧。虽然之前已经写过这方面的文章了，但现在结合着页面渲染更新一起来看下吧</p>
<p>推荐一个看的挺不错的<a target="_blank" rel="noopener" href="https://juejin.cn/post/6938702983014121485#heading-9">响应式原理的文章</a></p>
<p>注意使用这两个api创建响应式数据的时候，一般是在setup里面，而setup的初始化是在 setupComponent里面执行的，这里就会有一些上下文变量，主要是下一步的setupRenderEffect的时候，render函数使用h函数创建vnode的时候可能需要去获取到setup里面的数据，这时候就会触发依赖收集了，所以这个上下文就比较重要了</p>
<h5 id="reactive"><a href="#reactive" class="headerlink" title="reactive"></a>reactive</h5><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> reactiveMap = <span class="keyword">new</span> <span class="built_in">WeakMap</span>();</span><br><span class="line"><span class="keyword">const</span> mutableHandlers = &#123;</span><br><span class="line">    get,</span><br><span class="line">    set,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">reactive</span>(<span class="params">target</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> createReactiveObject(target, reactiveMap, mutableHandlers);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createReactiveObject</span>(<span class="params">target, proxyMap, baseHandlers</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> existingProxy = proxyMap.get(target);</span><br><span class="line">    <span class="keyword">if</span> (existingProxy) &#123;</span><br><span class="line">        <span class="keyword">return</span> existingProxy;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(target, baseHandlers);</span><br><span class="line">    proxyMap.set(target, proxy);</span><br><span class="line">    <span class="keyword">return</span> proxy;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>proxyMap是防止数据被多次代理的。上面的get和set才是重头戏</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> get = createGetter();</span><br><span class="line"><span class="keyword">const</span> set = createSetter();</span><br><span class="line"><span class="keyword">const</span> readonlyGet = createGetter(<span class="literal">true</span>);</span><br><span class="line"><span class="keyword">const</span> shallowReadonlyGet = createGetter(<span class="literal">true</span>, <span class="literal">true</span>);</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createGetter</span>(<span class="params">isReadonly = <span class="literal">false</span>, shallow = <span class="literal">false</span></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// receiver表示 Proxy或者继承Proxy的对象</span></span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">get</span>(<span class="params">target, key, receiver</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">const</span> isExistInReactiveMap = <span class="function">() =&gt;</span> key === <span class="string">&quot;__v_raw&quot;</span> &amp;&amp; receiver === reactiveMap.get(target);</span><br><span class="line">        <span class="keyword">const</span> isExistInReadonlyMap = <span class="function">() =&gt;</span> key === <span class="string">&quot;__v_raw&quot;</span> &amp;&amp; receiver === readonlyMap.get(target);</span><br><span class="line">        <span class="keyword">const</span> isExistInShallowReadonlyMap = <span class="function">() =&gt;</span> key === <span class="string">&quot;__v_raw&quot;</span> &amp;&amp; receiver === shallowReadonlyMap.get(target);</span><br><span class="line">        <span class="keyword">if</span> (key === <span class="string">&quot;__v_isReactive&quot;</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> !isReadonly;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (key === <span class="string">&quot;__v_isReadonly&quot;</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> isReadonly;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (isExistInReactiveMap() ||</span><br><span class="line">            isExistInReadonlyMap() ||</span><br><span class="line">            isExistInShallowReadonlyMap()) &#123;</span><br><span class="line">            <span class="keyword">return</span> target;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">const</span> res = <span class="built_in">Reflect</span>.get(target, key, receiver);</span><br><span class="line">        <span class="keyword">if</span> (shallow) &#123;</span><br><span class="line">            <span class="keyword">return</span> res;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (isObject(res)) &#123;</span><br><span class="line">            <span class="keyword">return</span> isReadonly ? readonly(res) : reactive(res);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (!isReadonly) &#123;</span><br><span class="line">            <span class="comment">// 依赖收集</span></span><br><span class="line">            track(target, <span class="string">&quot;get&quot;</span>, key);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createSetter</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">set</span>(<span class="params">target, key, value, receiver</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">const</span> result = <span class="built_in">Reflect</span>.set(target, key, value, receiver);</span><br><span class="line">        <span class="comment">// 依赖触发</span></span><br><span class="line">        trigger(target, <span class="string">&quot;get&quot;</span>, key);</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h6 id="get"><a href="#get" class="headerlink" title="get"></a>get</h6><p>先是几个内置的属性，如 __v_isReactive、__v_isReadonly，通过这些属性判断这个数据是如何被创建的。同时这也是vue3里面的 <strong>isReactive、isReadonly</strong> api的内部实现</p>
<p>然后是对 <strong>key=”__v_raw”</strong> 这个特殊属性的判断，表示获取其<strong>原始</strong>值，即没被proxy代理的原始对象。对应vue3的 <strong>toRaw</strong> api</p>
<p>然后就是对是否是<strong>shallow</strong>进行判断，是的话就直接返回数据。</p>
<p><a target="_blank" rel="noopener" href="https://v3.cn.vuejs.org/api/basic-reactivity.html#shallowreactive">shallowReactive</a>：创建一个响应式代理，它跟踪其自身 property 的响应性，但不执行嵌套对象的深层响应式转换 (暴露原始值)</p>
<p><a target="_blank" rel="noopener" href="https://v3.cn.vuejs.org/api/basic-reactivity.html#shallowreadonly">shallowReadonly</a>：创建一个 proxy，使其自身的 property 为只读，但不执行嵌套对象的深度只读转换 (暴露原始值)</p>
<p>后面就是对res是否为object和是否是readonly进行递归的响应式处理。其中<strong>readonly(res)<strong>基本逻辑与reactive基本相同，只是在proxy的handler里创建get方法时将</strong>createGetter</strong>的第一个参数设为了<strong>true</strong>，同时set方法不进行实际的数据修改</p>
<p>然后就是重要的</p>
<h6 id="依赖收集track"><a href="#依赖收集track" class="headerlink" title="依赖收集track"></a><strong>依赖收集track</strong></h6><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">track</span>(<span class="params">target, type, key</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!isTracking()) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`触发 track -&gt; target: <span class="subst">$&#123;target&#125;</span> type:<span class="subst">$&#123;type&#125;</span> key:<span class="subst">$&#123;key&#125;</span>`</span>);</span><br><span class="line">    <span class="keyword">let</span> depsMap = targetMap.get(target);</span><br><span class="line">    <span class="keyword">if</span> (!depsMap) &#123;</span><br><span class="line">        depsMap = <span class="keyword">new</span> <span class="built_in">Map</span>();</span><br><span class="line">        targetMap.set(target, depsMap);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> dep = depsMap.get(key);</span><br><span class="line">    <span class="keyword">if</span> (!dep) &#123;</span><br><span class="line">        dep = createDep();</span><br><span class="line">        depsMap.set(key, dep);</span><br><span class="line">    &#125;</span><br><span class="line">    trackEffects(dep);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">trackEffects</span>(<span class="params">dep</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 这个就需要联系一下上下文了。是在执行 setupRenderEffect 的时候所控制的值</span></span><br><span class="line">    <span class="keyword">if</span> (!dep.has(activeEffect)) &#123;</span><br><span class="line">        <span class="comment">// activeEffect是在ReactiveEffect的run方法里面用来指定this的，即使用ReactiveEffect创建的实例的this</span></span><br><span class="line">        dep.add(activeEffect);</span><br><span class="line">        activeEffect.deps.push(dep);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createDep</span>(<span class="params">effects</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> dep = <span class="keyword">new</span> <span class="built_in">Set</span>(effects);</span><br><span class="line">    <span class="keyword">return</span> dep;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>首先，一进去就看见了那个熟悉的结构 <strong>{target:{key:[eff1，eff2]}}</strong> ，以至于我都不想写了。简单的说就是将每一个effct都加入到一个set中，然后trigger的时候就去这个key对应的set中挨个执行</p>
<h6 id="set"><a href="#set" class="headerlink" title="set"></a>set</h6><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">trigger(target, <span class="string">&quot;get&quot;</span>, key);</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">trigger</span>(<span class="params">target, type, key</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> deps = [];</span><br><span class="line">    <span class="keyword">const</span> depsMap = targetMap.get(target);</span><br><span class="line">    <span class="keyword">const</span> dep = depsMap.get(key);</span><br><span class="line">    deps.push(dep);</span><br><span class="line">    <span class="keyword">const</span> effects = [];</span><br><span class="line">    deps.forEach(<span class="function">(<span class="params">dep</span>) =&gt;</span> &#123;</span><br><span class="line">        effects.push(...dep);</span><br><span class="line">    &#125;);</span><br><span class="line">    triggerEffects(createDep(effects));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">triggerEffects</span>(<span class="params">dep</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> effect <span class="keyword">of</span> dep) &#123;</span><br><span class="line">        <span class="keyword">if</span> (effect.scheduler) &#123;</span><br><span class="line">            effect.scheduler();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            effect.run();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>就差不多这个代码吧，一眼就能看懂，比较详细的解释看后面的ref吧</p>
<h5 id="computed"><a href="#computed" class="headerlink" title="computed"></a>computed</h5><p>实际上也大差不差，返回一个不可变的响应式ref对象</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ComputedRefImpl</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">getter</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>._dirty = <span class="literal">true</span>;</span><br><span class="line">        <span class="built_in">this</span>.dep = createDep();</span><br><span class="line">        <span class="built_in">this</span>.effect = <span class="keyword">new</span> ReactiveEffect(getter, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="built_in">this</span>._dirty)</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            <span class="built_in">this</span>._dirty = <span class="literal">true</span>;</span><br><span class="line">            triggerRefValue(<span class="built_in">this</span>);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">get</span> <span class="title">value</span>() &#123;</span><br><span class="line">        trackRefValue(<span class="built_in">this</span>);</span><br><span class="line">        <span class="keyword">if</span> (<span class="built_in">this</span>._dirty) &#123;</span><br><span class="line">            <span class="built_in">this</span>._dirty = <span class="literal">false</span>;</span><br><span class="line">            <span class="built_in">this</span>._value = <span class="built_in">this</span>.effect.run();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>._value;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">computed</span>(<span class="params">getter</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> ComputedRefImpl(getter);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h5 id="ref"><a href="#ref" class="headerlink" title="ref"></a>ref</h5><p>注意如果传入的是一个object的话，内部是用reactive实现的</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ref</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> createRef(value);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">convert</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> isObject(value) ? reactive(value) : value;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createRef</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> refImpl = <span class="keyword">new</span> RefImpl(value);</span><br><span class="line">    <span class="keyword">return</span> refImpl;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RefImpl</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">value</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.__v_isRef = <span class="literal">true</span>;</span><br><span class="line">        <span class="built_in">this</span>._rawValue = value;</span><br><span class="line">        <span class="built_in">this</span>._value = convert(value);</span><br><span class="line">        <span class="built_in">this</span>.dep = createDep();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">get</span> <span class="title">value</span>() &#123;</span><br><span class="line">        trackRefValue(<span class="built_in">this</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>._value;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">set</span> <span class="title">value</span>(<span class="params">newValue</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (hasChanged(newValue, <span class="built_in">this</span>._rawValue)) &#123;</span><br><span class="line">            <span class="built_in">this</span>._value = convert(newValue);</span><br><span class="line">            <span class="built_in">this</span>._rawValue = newValue;</span><br><span class="line">            triggerRefValue(<span class="built_in">this</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">hasChanged</span>(<span class="params">value, oldValue</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> !<span class="built_in">Object</span>.is(value, oldValue);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createDep</span>(<span class="params">effects</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> dep = <span class="keyword">new</span> <span class="built_in">Set</span>(effects);</span><br><span class="line">    <span class="keyword">return</span> dep;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意里面的 <strong>__v_isRef</strong> ，通过这个属性，判断其实通过ref创建的。dep是用来配合依赖收集和触发更新的</p>
<p>然后里面的 <strong>get value() 和 set value(newValue)</strong> 是class的语法，</p>
<p>value相当于new出来的实例的属性，如 refImpl.value 就对应get value() 。refImpl.value=10 就对应set value()。</p>
<p>然后似乎这里就没有使用proxy来控制get和set了。就直接使用class语法提供的get和set控制依赖收集和触发更新</p>
<h6 id="依赖收集trackRefValue"><a href="#依赖收集trackRefValue" class="headerlink" title="依赖收集trackRefValue"></a>依赖收集trackRefValue</h6><p>因为是在get里面进行依赖收集的，所以其使用场景在这个componentUpdate目录里就是render函数里的h函数创建vnode的时候，传入<strong>props</strong>可能会get这些变量，然后触发依赖收集</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">trackRefValue</span>(<span class="params">ref</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (isTracking()) &#123;</span><br><span class="line">        trackEffects(ref.dep);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isTracking</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> shouldTrack &amp;&amp; activeEffect !== <span class="literal">undefined</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">trackEffects</span>(<span class="params">dep</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!dep.has(activeEffect)) &#123;</span><br><span class="line">        <span class="comment">// activeEffect是在ReactiveEffect的run方法里面用来指定this的，即使用ReactiveEffect创建的实例的this</span></span><br><span class="line">        dep.add(activeEffect);</span><br><span class="line">        activeEffect.deps.push(dep);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>里面的shouldTrack &amp;&amp; activeEffect是在 ReactiveEffect class里面的run方法里面的。表示是否能够收集依赖。</p>
<p><a target="_blank" rel="noopener" href="https://juejin.cn/post/6938702983014121485#heading-5">上面的是否允许进行依赖收集，有一个详细解释的例子</a>，简单的说就是重新执行effect更新数据的时候，effect里面去获取数据的时候，如果没有上面的收集控制，则又会触发一次get和无效的track，所以需要进行控制</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="title">run</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;run&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span> (!<span class="built_in">this</span>.active) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.fn();</span><br><span class="line">    &#125;</span><br><span class="line">    shouldTrack = <span class="literal">true</span>;</span><br><span class="line">    activeEffect = <span class="built_in">this</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;执行用户传入的 fn&quot;</span>);</span><br><span class="line">    <span class="keyword">const</span> result = <span class="built_in">this</span>.fn();</span><br><span class="line">    shouldTrack = <span class="literal">false</span>;</span><br><span class="line">    activeEffect = <span class="literal">undefined</span>;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h6 id="依赖触发triggerRefValue"><a href="#依赖触发triggerRefValue" class="headerlink" title="依赖触发triggerRefValue"></a>依赖触发triggerRefValue</h6><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">set</span> <span class="title">value</span>(<span class="params">newValue</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (hasChanged(newValue, <span class="built_in">this</span>._rawValue)) &#123;</span><br><span class="line">        <span class="built_in">this</span>._value = convert(newValue);</span><br><span class="line">        <span class="built_in">this</span>._rawValue = newValue;</span><br><span class="line">        triggerRefValue(<span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">triggerRefValue</span>(<span class="params">ref</span>) </span>&#123;</span><br><span class="line">    triggerEffects(ref.dep);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">triggerEffects</span>(<span class="params">dep</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> effect <span class="keyword">of</span> dep) &#123;</span><br><span class="line">        <span class="keyword">if</span> (effect.scheduler) &#123;</span><br><span class="line">            effect.scheduler();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            effect.run();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里就可以看出，依赖触发的时候，就是执行dep里面存的<strong>ReactiveEffect实例</strong>的scheduler或run方法</p>
<p>传入的方法目前是在<strong>setupRenderEffect</strong>里面使用effect传入的组件更新的方法，同时还传递了一个scheduler的方法，并合并到ReactiveEffect实例上去</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">instance.update = effect(componentUpdateFn, &#123;</span><br><span class="line">    <span class="attr">scheduler</span>: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;scheduler执行&#x27;</span>)</span><br><span class="line">        queueJob(instance.update);</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">effect</span>(<span class="params">fn, options = &#123;&#125;</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> _effect = <span class="keyword">new</span> ReactiveEffect(fn);</span><br><span class="line">    extend(_effect, options);</span><br><span class="line">    _effect.run();</span><br><span class="line">    <span class="keyword">const</span> runner = _effect.run.bind(_effect);</span><br><span class="line">    runner.effect = _effect;</span><br><span class="line">    <span class="keyword">return</span> runner;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>好，现在当我们<strong>点击了按钮之后，修改了ref的值。</strong></p>
<p>因为现在的ref.dep还只有一个元素，同时这个元素还有scheduler，所以就执行scheduler了。</p>
<p>TODO：scheduler是为了让更新推到微任务里面执行</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> queue = [];</span><br><span class="line"><span class="comment">// 注意这个promise，微任务执行</span></span><br><span class="line"><span class="keyword">const</span> p = <span class="built_in">Promise</span>.resolve();</span><br><span class="line"><span class="keyword">let</span> isFlushPending = <span class="literal">false</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">nextTick</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> fn ? p.then(fn) : p;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">queueJob</span>(<span class="params">job</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!queue.includes(job)) &#123;</span><br><span class="line">        queue.push(job);</span><br><span class="line">        queueFlush();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">queueFlush</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (isFlushPending)</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    isFlushPending = <span class="literal">true</span>;</span><br><span class="line">    nextTick(flushJobs);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">flushJobs</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    isFlushPending = <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">let</span> job;</span><br><span class="line">    <span class="keyword">while</span> ((job = queue.shift())) &#123;</span><br><span class="line">        <span class="keyword">if</span> (job) &#123;</span><br><span class="line">            job();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看见就是将dep里面的每一个effect都使用promise包装一下进行调用。最终还是调用<strong>setupRenderEffect</strong>里面使用effect传入的组件更新的方法<strong>componentUpdateFn</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">componentUpdateFn</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!instance.isMounted) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;调用 render,获取 subTree&quot;</span>);</span><br><span class="line">        <span class="keyword">const</span> proxyToUse = instance.proxy;</span><br><span class="line">        <span class="comment">// 初始化时 instance.render = Component.render;</span></span><br><span class="line">        <span class="comment">// render函数是使用h函数创建出来vnode</span></span><br><span class="line">        <span class="comment">// 这里传入proxyToUse当做this是因为可能在h函数里面会访问到setup函数返回的数据</span></span><br><span class="line">        <span class="keyword">const</span> subTree = (instance.subTree = instance.render.call(proxyToUse, proxyToUse));</span><br><span class="line">        <span class="comment">// console.log(&#x27;proxyToUse: &#x27;, proxyToUse);</span></span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;subTree&quot;</span>, subTree);</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;instance.type.name&#125;</span>:触发 beforeMount hook`</span>);</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;instance.type.name&#125;</span>:触发 onVnodeBeforeMount hook`</span>);</span><br><span class="line">        patch(<span class="literal">null</span>, subTree, container, instance);</span><br><span class="line">        initialVNode.el = subTree.el;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;instance.type.name&#125;</span>:触发 mounted hook`</span>);</span><br><span class="line">        instance.isMounted = <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;调用更新逻辑&quot;</span>);</span><br><span class="line">        <span class="keyword">const</span> &#123; next, vnode &#125; = instance;</span><br><span class="line">        <span class="keyword">if</span> (next) &#123;</span><br><span class="line">            next.el = vnode.el;</span><br><span class="line">            updateComponentPreRender(instance, next);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">const</span> proxyToUse = instance.proxy;</span><br><span class="line">        <span class="comment">// 重新执行render函数是为了获取到最新的数据</span></span><br><span class="line">        <span class="keyword">const</span> nextTree = instance.render.call(proxyToUse, proxyToUse);</span><br><span class="line">        <span class="keyword">const</span> prevTree = instance.subTree;</span><br><span class="line">        instance.subTree = nextTree;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;beforeUpdated hook&quot;</span>);</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;onVnodeBeforeUpdate hook&quot;</span>);</span><br><span class="line">        patch(prevTree, nextTree, prevTree.el, instance);</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;updated hook&quot;</span>);</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;onVnodeUpdated hook&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这一次因为组件已经mount了，所以执行update的逻辑</p>
<p>TODO：这里面的<strong>next</strong>是啥还不清楚。— next是vnode的props修改后的新生成的vnode，通过这个就可以知道哪些东西要更新</p>
<p>然后重头戏来了，patch里面新旧节点进行对比更新</p>
<h5 id="patch新旧节点对比"><a href="#patch新旧节点对比" class="headerlink" title="patch新旧节点对比"></a>patch新旧节点对比</h5><p>这里就只看操作，对比的原理就看其他的了</p>
<p><a target="_blank" rel="noopener" href="https://cansiny0320.vercel.app/vue-diff#patch">推荐文章</a></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">patch</span>(<span class="params">n1, n2, container = <span class="literal">null</span>, parentComponent = <span class="literal">null</span></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; type, shapeFlag &#125; = n2;</span><br><span class="line">    <span class="keyword">switch</span> (type) &#123;</span><br><span class="line">        <span class="keyword">case</span> Text:</span><br><span class="line">            processText(n1, n2, container);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">if</span> (shapeFlag &amp; <span class="number">1</span>) &#123;</span><br><span class="line">                <span class="built_in">console</span>.log(<span class="string">&quot;处理 element&quot;</span>);</span><br><span class="line">                processElement(n1, n2, container);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (shapeFlag &amp; <span class="number">4</span>) &#123;</span><br><span class="line">                <span class="built_in">console</span>.log(<span class="string">&quot;处理 component&quot;</span>);</span><br><span class="line">                processComponent(n1, n2, container, parentComponent);</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h6 id="element类型"><a href="#element类型" class="headerlink" title="element类型"></a>element类型</h6><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">processElement</span>(<span class="params">n1, n2, container</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!n1) &#123;</span><br><span class="line">        mountElement(n2, container);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        updateElement(n1, n2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">updateElement</span>(<span class="params">n1, n2, container</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> oldProps = (n1 &amp;&amp; n1.props) || &#123;&#125;;</span><br><span class="line">    <span class="keyword">const</span> newProps = n2.props || &#123;&#125;;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;应该更新 element&quot;</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;旧的 vnode&quot;</span>, n1);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;新的 vnode&quot;</span>, n2);</span><br><span class="line">    <span class="keyword">const</span> el = (n2.el = n1.el);</span><br><span class="line">    patchProps(el, oldProps, newProps);</span><br><span class="line">    patchChildren(n1, n2, el);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>先对props和el进行操作比对。</p>
<p>TODO：不清楚 <strong>el = (n2.el = n1.el)</strong> 这一段为什么n2.el要被n1赋值。– 保持原有的真实dom，这里默认了其type是一样的</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">patchProps</span>(<span class="params">el, oldProps, newProps</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">in</span> newProps) &#123;</span><br><span class="line">        <span class="keyword">const</span> prevProp = oldProps[key];</span><br><span class="line">        <span class="keyword">const</span> nextProp = newProps[key];</span><br><span class="line">        <span class="keyword">if</span> (prevProp !== nextProp) &#123;</span><br><span class="line">            hostPatchProp(el, key, prevProp, nextProp);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">in</span> oldProps) &#123;</span><br><span class="line">        <span class="keyword">const</span> prevProp = oldProps[key];</span><br><span class="line">        <span class="keyword">const</span> nextProp = <span class="literal">null</span>;</span><br><span class="line">        <span class="keyword">if</span> (!(key <span class="keyword">in</span> newProps)) &#123;</span><br><span class="line">            hostPatchProp(el, key, prevProp, nextProp);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>先将新的props的所有key绑定到el上，然后将旧的props的所有没有在新的props存在的属性给去除</p>
<p><strong>再对孩子节点进行对比</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">patchChildren</span>(<span class="params">n1, n2, container</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; <span class="attr">shapeFlag</span>: prevShapeFlag, <span class="attr">children</span>: c1 &#125; = n1;</span><br><span class="line">    <span class="keyword">const</span> &#123; shapeFlag, <span class="attr">children</span>: c2 &#125; = n2;</span><br><span class="line">    <span class="keyword">if</span> (shapeFlag &amp; <span class="number">8</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (c2 !== c1) &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;类型为 text_children, 当前需要更新&quot;</span>);</span><br><span class="line">            hostSetElementText(container, c2);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (prevShapeFlag &amp; <span class="number">16</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (shapeFlag &amp; <span class="number">16</span>) &#123;</span><br><span class="line">                patchKeyedChildren(c1, c2, container);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果新vnode是一个文本节点，即其children是一个text，那么久直接进行更新，不再比较</p>
<p>上面的 <strong>16</strong> 表示是一个array children</p>
<h6 id="component类型对比"><a href="#component类型对比" class="headerlink" title="component类型对比"></a>component类型对比</h6><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">processComponent</span>(<span class="params">n1, n2, container, parentComponent</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!n1) &#123;</span><br><span class="line">        mountComponent(n2, container, parentComponent);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        updateComponent(n1, n2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">updateComponent</span>(<span class="params">n1, n2, container</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;更新组件&quot;</span>, n1, n2);</span><br><span class="line">    <span class="keyword">const</span> instance = (n2.component = n1.component);</span><br><span class="line">    <span class="keyword">if</span> (shouldUpdateComponent(n1, n2)) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`组件需要更新: <span class="subst">$&#123;instance&#125;</span>`</span>);</span><br><span class="line">        instance.next = n2;</span><br><span class="line">        instance.update();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`组件不需要更新: <span class="subst">$&#123;instance&#125;</span>`</span>);</span><br><span class="line">        n2.component = n1.component;</span><br><span class="line">        n2.el = n1.el;</span><br><span class="line">        instance.vnode = n2;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h5 id="patch重头戏"><a href="#patch重头戏" class="headerlink" title="patch重头戏"></a>patch重头戏</h5><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">patchKeyedChildren</span>(<span class="params">c1, c2, container</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">let</span> e1 = c1.length - <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">let</span> e2 = c2.length - <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">const</span> isSameVNodeType = <span class="function">(<span class="params">n1, n2</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> n1.type === n2.type &amp;&amp; n1.key === n2.key;</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">while</span> (i &lt;= e1 &amp;&amp; i &lt;= e2) &#123;</span><br><span class="line">        <span class="keyword">const</span> prevChild = c1[i];</span><br><span class="line">        <span class="keyword">const</span> nextChild = c2[i];</span><br><span class="line">        <span class="keyword">if</span> (!isSameVNodeType(prevChild, nextChild)) &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;两个 child 不相等(从左往右比对)&quot;</span>);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">`prevChild:<span class="subst">$&#123;prevChild&#125;</span>`</span>);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">`nextChild:<span class="subst">$&#123;nextChild&#125;</span>`</span>);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;两个 child 相等，接下来对比这两个 child 节点(从左往右比对)&quot;</span>);</span><br><span class="line">        patch(prevChild, nextChild, container);</span><br><span class="line">        i++;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">// 注意这里必定是经过上面break后才会进入执行</span></span><br><span class="line">    <span class="keyword">while</span> (i &lt;= e1 &amp;&amp; i &lt;= e2) &#123;</span><br><span class="line">        <span class="keyword">const</span> prevChild = c1[e1];</span><br><span class="line">        <span class="keyword">const</span> nextChild = c2[e2];</span><br><span class="line">        <span class="keyword">if</span> (!isSameVNodeType(prevChild, nextChild)) &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;两个 child 不相等(从右往左比对)&quot;</span>);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">`prevChild:<span class="subst">$&#123;prevChild&#125;</span>`</span>);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">`nextChild:<span class="subst">$&#123;nextChild&#125;</span>`</span>);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;两个 child 相等，接下来对比着两个 child 节点(从右往左比对)&quot;</span>);</span><br><span class="line">        patch(prevChild, nextChild, container);</span><br><span class="line">        e1--;</span><br><span class="line">        e2--;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (i &gt; e1 &amp;&amp; i &lt;= e2) &#123;</span><br><span class="line">        <span class="keyword">while</span> (i &lt;= e2) &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">`需要新创建一个 vnode: <span class="subst">$&#123;c2[i].key&#125;</span>`</span>);</span><br><span class="line">            patch(<span class="literal">null</span>, c2[i], container);</span><br><span class="line">            i++;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (i &gt; e2 &amp;&amp; i &lt;= e1) &#123;</span><br><span class="line">        <span class="keyword">while</span> (i &lt;= e1) &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">`需要删除当前的 vnode: <span class="subst">$&#123;c1[i].key&#125;</span>`</span>);</span><br><span class="line">            hostRemove(c1[i].el);</span><br><span class="line">            i++;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> s1 = i;</span><br><span class="line">        <span class="keyword">let</span> s2 = i;</span><br><span class="line">        <span class="keyword">const</span> keyToNewIndexMap = <span class="keyword">new</span> <span class="built_in">Map</span>();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> i = s2; i &lt;= e2; i++) &#123;</span><br><span class="line">            <span class="keyword">const</span> nextChild = c2[i];</span><br><span class="line">            keyToNewIndexMap.set(nextChild.key, i);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">const</span> toBePatched = e2 - s2 + <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">const</span> newIndexToOldIndexMap = <span class="keyword">new</span> <span class="built_in">Array</span>(toBePatched);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> index = <span class="number">0</span>; index &lt; newIndexToOldIndexMap.length; index++) &#123;</span><br><span class="line">            newIndexToOldIndexMap[index] = -<span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (i = s1; i &lt;= e1; i++) &#123;</span><br><span class="line">            <span class="keyword">const</span> prevChild = c1[i];</span><br><span class="line">            <span class="keyword">const</span> newIndex = keyToNewIndexMap.get(prevChild.key);</span><br><span class="line">            newIndexToOldIndexMap[newIndex] = i;</span><br><span class="line">            <span class="keyword">if</span> (newIndex === <span class="literal">undefined</span>) &#123;</span><br><span class="line">                hostRemove(prevChild.el);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="built_in">console</span>.log(<span class="string">&quot;新老节点都存在&quot;</span>);</span><br><span class="line">                patch(prevChild, c2[newIndex], container);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (i = e2; i &gt;= s2; i--) &#123;</span><br><span class="line">            <span class="keyword">const</span> nextChild = c2[i];</span><br><span class="line">            <span class="keyword">if</span> (newIndexToOldIndexMap[i] === -<span class="number">1</span>) &#123;</span><br><span class="line">                patch(<span class="literal">null</span>, c2[i], container);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">const</span> anchor = i + <span class="number">1</span> &gt;= e2 + <span class="number">1</span> ? <span class="literal">null</span> : c2[i + <span class="number">1</span>];</span><br><span class="line">                hostInsert(nextChild.el, container, anchor &amp;&amp; anchor.el);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>TODO：在这里例子里面，<strong>isSameVNodeType</strong> 对使用同一个子组件创建的vnode是认为一样的</p>
<p>即使用这两句创建出来的vnode</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">instance.subTree = instance.render.call(proxyToUse, proxyToUse);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> nextTree = instance.render.call(proxyToUse, proxyToUse);</span><br><span class="line"><span class="keyword">const</span> prevTree = instance.subTree;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="title">render</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> h(<span class="string">&quot;div&quot;</span>, &#123;&#125;, [</span><br><span class="line">      h(<span class="string">&quot;div&quot;</span>, &#123;&#125;, <span class="string">&quot;你好&quot;</span>),</span><br><span class="line">      h(</span><br><span class="line">        <span class="string">&quot;button&quot;</span>,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">onClick</span>: <span class="built_in">this</span>.changeChildProps,</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="string">&quot;change child props&quot;</span></span><br><span class="line">      ),</span><br><span class="line">      h(Child, &#123;</span><br><span class="line">        <span class="attr">msg</span>: <span class="built_in">this</span>.msg,</span><br><span class="line">      &#125;),</span><br><span class="line">    ]);</span><br><span class="line">  &#125;,</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> isSameVNodeType = <span class="function">(<span class="params">n1, n2</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> n1.type === n2.type &amp;&amp; n1.key === n2.key;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>即上面的render函数的 h(Child, { msg: this.msg, }) 使用了 **child    **这个子组件创建的，而我们现在改变了props msg的值，但child是没有变的，还是同一个来源。同时在创建vnode的时候</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> createVNode = <span class="function"><span class="keyword">function</span> (<span class="params">type, props, children</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> vnode = &#123;</span><br><span class="line">        <span class="attr">el</span>: <span class="literal">null</span>,</span><br><span class="line">        <span class="attr">component</span>: <span class="literal">null</span>,</span><br><span class="line">        <span class="attr">key</span>: props === <span class="literal">null</span> || props === <span class="keyword">void</span> <span class="number">0</span> ? <span class="keyword">void</span> <span class="number">0</span> : props.key,</span><br><span class="line">        type,</span><br><span class="line">        <span class="attr">props</span>: props || &#123;&#125;,</span><br><span class="line">        children,</span><br><span class="line">        <span class="attr">shapeFlag</span>: getShapeFlag(type),</span><br><span class="line">    &#125;;</span><br><span class="line">    ...&#125;</span><br></pre></td></tr></table></figure>

<p>可以看出是直接将type形参传入的，所以在 <strong>isSameVNodeType</strong> 里面可以判断出是同一个组件type创建的</p>
<p>然后如果vnodeType相同的话，后面就会执行一次patch操作，去对同类型的节点进行更新。这里就主要是更新child这个<strong>component</strong></p>
<p>TODO：n2.component = n1.component 这一步又是干啥</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">updateComponent</span>(<span class="params">n1, n2, container</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;更新组件&quot;</span>, n1, n2);</span><br><span class="line">    <span class="keyword">const</span> instance = (n2.component = n1.component);</span><br><span class="line">    <span class="keyword">if</span> (shouldUpdateComponent(n1, n2)) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`组件需要更新: <span class="subst">$&#123;instance&#125;</span>`</span>);</span><br><span class="line">        instance.next = n2;</span><br><span class="line">        instance.update();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`组件不需要更新: <span class="subst">$&#123;instance&#125;</span>`</span>);</span><br><span class="line">        n2.component = n1.component;</span><br><span class="line">        n2.el = n1.el;</span><br><span class="line">        instance.vnode = n2;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">shouldUpdateComponent</span>(<span class="params">prevVNode, nextVNode</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; <span class="attr">props</span>: prevProps &#125; = prevVNode;</span><br><span class="line">    <span class="keyword">const</span> &#123; <span class="attr">props</span>: nextProps &#125; = nextVNode;</span><br><span class="line">    <span class="keyword">if</span> (prevProps === nextProps) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (!prevProps) &#123;</span><br><span class="line">        <span class="keyword">return</span> !!nextProps;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (!nextProps) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> hasPropsChanged(prevProps, nextProps);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">hasPropsChanged</span>(<span class="params">prevProps, nextProps</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> nextKeys = <span class="built_in">Object</span>.keys(nextProps);</span><br><span class="line">    <span class="keyword">if</span> (nextKeys.length !== <span class="built_in">Object</span>.keys(prevProps).length) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; nextKeys.length; i++) &#123;</span><br><span class="line">        <span class="keyword">const</span> key = nextKeys[i];</span><br><span class="line">        <span class="keyword">if</span> (nextProps[key] !== prevProps[key]) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>首先是根据两个节点的props是否相同判断是否更新，如果不同则进行更新。</p>
<p>instance.next = n2; 这一步是为了后面执行更新逻辑的时候可以知道要更新哪些东西</p>
<p>后面就是执行instance（n1）的update方法，即最终的<strong>componentUpdateFn</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">instance.update = effect(componentUpdateFn, &#123;</span><br><span class="line">    <span class="attr">scheduler</span>: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;scheduler执行&#x27;</span>)</span><br><span class="line">        queueJob(instance.update);</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;调用更新逻辑&quot;</span>);</span><br><span class="line">    <span class="keyword">const</span> &#123; next, vnode &#125; = instance;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;instance: &#x27;</span>, instance);</span><br><span class="line">    <span class="keyword">if</span> (next) &#123;</span><br><span class="line">        next.el = vnode.el;</span><br><span class="line">        updateComponentPreRender(instance, next);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> proxyToUse = instance.proxy;</span><br><span class="line">    <span class="comment">// 重新执行render函数是为了获取到最新的数据</span></span><br><span class="line">    <span class="keyword">const</span> nextTree = instance.render.call(proxyToUse, proxyToUse);</span><br><span class="line">    <span class="keyword">const</span> prevTree = instance.subTree;</span><br><span class="line"></span><br><span class="line">    instance.subTree = nextTree;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;beforeUpdated hook&quot;</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;onVnodeBeforeUpdate hook&quot;</span>);</span><br><span class="line">    patch(prevTree, nextTree, prevTree.el, instance);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;updated hook&quot;</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;onVnodeUpdated hook&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">updateComponentPreRender</span>(<span class="params">instance, nextVNode</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; props &#125; = nextVNode;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;更新组件的 props&quot;</span>, props);</span><br><span class="line">    instance.props = props;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;更新组件的 slots&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>因为这次有<strong>next</strong>了，所以进入updateComponentPreRender，这里应该就是简单的将props直接赋值，同时还有一些更新slots的逻辑</p>
<p>然后就是重新patch进行比对更新，这里就是更新其text_chldren的值</p>
<p>目前只走了第一个while循环进行对比，后面的循环看下一个文件继续进行理解。</p>
<h6 id="好，继续下一个循环"><a href="#好，继续下一个循环" class="headerlink" title="好，继续下一个循环"></a>好，继续下一个循环</h6><p>当上一个while发现child不同的时候才会进入执行。然后从右向左进行比较</p>
<p>下面就是处理当两个节点的child数量不一致的情况，如新节点的数量大于旧节点的数量，使用</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">patch(<span class="literal">null</span>, c2[i], container);</span><br></pre></td></tr></table></figure>

<p>从新patch进行创建和插入。</p>
<p>如相反，则对旧的多余节点进行删除操作</p>
<h6 id="最后的处理"><a href="#最后的处理" class="headerlink" title="最后的处理"></a>最后的处理</h6><p>就是前后都循环对比了一次了，剩下的就是中间那一部分顺序变化了的情况，如</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// a,b,[c,d,e],f,g</span></span><br><span class="line"><span class="comment">// a,b,[e,c,d],f,g</span></span><br></pre></td></tr></table></figure>

<p>主要利用了节点的key，通过key确定位置。</p>
<p>然后遍历老节点，找出老节点有，而新节点没有的，进行删除。都有的则进行patch。</p>
<p>遍历新节点，找出新节点有，而老节点没有的，进行创建。</p>
<p>最后移动位置</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">hostInsert</span>(<span class="params">child, parent, anchor = <span class="literal">null</span></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;hostInsert&quot;</span>);</span><br><span class="line">  <span class="keyword">if</span> (anchor) &#123;</span><br><span class="line">    <span class="comment">// 第二个参数表示要添加新的节点前的子节点。就是child要添加到这个anchor节点前面</span></span><br><span class="line">    parent.insertBefore(child, anchor);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    parent.appendChild(child);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (i = e2; i &gt;= s2; i--) &#123;</span><br><span class="line">  <span class="keyword">const</span> nextChild = c2[i];</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (newIndexToOldIndexMap[i] === -<span class="number">1</span>) &#123;</span><br><span class="line">    <span class="comment">// 说明是个新增的节点</span></span><br><span class="line">    patch(<span class="literal">null</span>, c2[i], container);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// 有可能 i+1 没有元素 没有的话就直接设置为 null</span></span><br><span class="line">    <span class="comment">// 在 hostInsert 函数内如果发现是 null 的话，会直接添加到父级容器内</span></span><br><span class="line">    <span class="keyword">const</span> anchor = i + <span class="number">1</span> &gt;= e2 + <span class="number">1</span> ? <span class="literal">null</span> : c2[i + <span class="number">1</span>];</span><br><span class="line">    hostInsert(nextChild.el, container, anchor &amp;&amp; anchor.el);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">晟松</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://chengsong.info/2021/11/19/mini-vue3学习记录/">https://chengsong.info/2021/11/19/mini-vue3学习记录/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://chengsong.info">晟松</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/vue3-%E6%BA%90%E7%A0%81/">vue3 源码</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2021/11/19/react%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95/"><i class="fa fa-chevron-left">  </i><span>react简单学习记录</span></a></div><div class="next-post pull-right"><a href="/2021/11/19/springboot%E7%AE%80%E5%8D%95%E5%AD%A6%E4%B9%A0/"><span>springboot入门</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer class="footer-bg" style="background-image: url(/img/blog-bg.jpg)"><div class="layout" id="footer"><div class="copyright">&copy;2020 - 2023 By 晟松</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="icp"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><span>湘ICP备2020021729号</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>